let data = {};
let editingId = null;
let requestUrl = null;
let typeArray = [null, "基础属性", "附加属性", "外观追加"];

/**
 * 宠物装备类型
 */
let equipmentTypes = [{
	type: 0,
	name: "无",
	selector: "#"
},{
	type: 1,
	name: "护腕",
	selector: "#hw"
}, {
	type: 2,
	name: "项圈",
	selector: "#xq"
}, {
	type: 3,
	name: "铠甲",
	selector: "#kj"
}];

function addHandler() {
	requestUrl = "/chongwu_equipment/insert";

	$("#score").numberspinner("setValue", 0);
	$("#waiguanId").combobox("setValue", 0);
	$("#taozhuangId").combobox("setValue", 0);

	$("#equipment_dialog").dialog("open");
}

function editHandler() {
	let rowData = $("#equipment_list").datagrid("getSelected");
	
	if (rowData) {
		requestUrl = "/chongwu_equipment/updateById";

		$("#id").val(rowData.id);
		$("#forger").textbox("setValue", rowData.forger);
		$("#roleId").combobox("setValue", rowData.roleId);
		$("#score").numberspinner("setValue", rowData.score);
		$("#waiguanId").combobox("setValue", rowData.waiguanId);
		$("#categoryId").combobox("setValue", rowData.categoryId);
		$("#taozhuangId").combobox("setValue", rowData.taozhuangId);

		$("#equipment_dialog").dialog("open");
	} else {
		alertMsg("请选择要修改的记录！");
	}
}

function attributeHandler() {
	let rowData = $("#equipment_list").datagrid("getSelected");

	if (rowData) {
		requestUrl = "/chongwu_equipment_attribute/updateById";

		$("#equipment_datalist").datalist("reload", {
			callback: function () {
				$("#equipment_datalist").datalist("selectRecord", rowData.id);
			}
		});

		$("#property_dialog").dialog("open");
	} else {
		unselected();
	}
}

function viewHandler() {
	// 宠物装备属性
	$("#property_white").empty();
	$("#property_green").empty().hide();
	$("#property_waiguan").empty().hide();
	$("#property_blue").empty().hide();
	// 星石属性
	$("#xingshi").hide();
	$("#property_xingshi_base").empty().hide();
	$("#property_xingshi_fuling").empty().hide();
	$("#property_xianghun").empty().hide();

	let rowData = $("#equipment_list").datagrid("getSelected");

	if (rowData) {
		// 宠物装备详情——基本信息
		ajaxGet("/chongwu_equipment_category/selectById", {
			id: rowData.categoryId
		}, function (resp) {
			let data = resp.data;

			$("#equipment_name").html(data.name);
			$("#equipment_note").html(data.note);
			$("#equipment_grade").html(data.grade);
			$("#equipment_image").attr("src", data.image);
			$("#equipment_type").html(equipmentTypes[data.type].name);
		}, error);

		// 查询宠物装备总评分
		ajaxGet("/chongwu_equipment/getTotalScore", {
			equipmentId: rowData.id
		}, function (resp) {
			$("#equipment_score").html(resp.data);
		}, error);

		// 查询宠物装备属性
		ajaxGet("/chongwu_equipment_attribute/selectAttributes", {
			equipmentId: rowData.id
		}, function (resp) {
			let data = resp.data;

			if (data.length > 0) {
				$("#property").show();

				for (let i = 0; i < data.length; i++) {
					let attribute = data[i];

					if (attribute.propertyType === 1) { // 基础属性
						$("#property_white").html("&emsp;" + attribute.propertyName + "&ensp;+" + attribute.propertyValue);
					} else if (attribute.propertyType === 2) { // 附加属性
						$("#property_green").append("&emsp;" + attribute.propertyName + "+" + attribute.propertyValue  + "&emsp;").show();
					} else if (attribute.propertyType === 3) { // 外观追加属性
						let content = "&emsp;外观追加&ensp;" + attribute.propertyName + "+" + attribute.propertyValue;

						$("#property_waiguan").html(content).show();
					}
				}
			}
		}, error);

		// 查询宠物装备镶嵌的星石
		ajaxGet("/xingshi/selectByEquipmentId", {
			equipmentId: rowData.id
		}, function (resp) {
			let data = resp.data;

			if (data) {
				$("#xingshi").show();

				let xingshiId = data.id;

				/**
				 * 查询星石属性
				 */
				ajaxGet("/xingshi/selectAttribute", {
					xingshiId: xingshiId
				}, function (resp) {
					let attribute = resp.data;

					if (attribute) {
						let property = "&emsp;" + data.grade + "级" + attribute.name;

						property += "&ensp;" + attribute.propertyName + "&ensp;+" + attribute.propertyValue;

						$("#property_xingshi_base").append(property).show();
					}
				}, error);

				/**
				 * 查询星石的附灵信息
				 */
				ajaxGet("/xingshi_fuling/selectAttributes", {
					xingshiId: xingshiId
				}, function (resp) {
					let data = resp.data;

					if (data && data.length > 0) {
						let content = "&emsp;";

						for (let i = 0; i <= data.length - 1; i++) {
							content += data[i].propertyName + "+" + data[i].propertyValue;

							if (i < data.length - 1) {
								content += "&emsp;&emsp;";
							}
						}

						$("#property_xingshi_fuling").append(content).show();
					}
				}, error);

				/**
				 * 查询星石的相魂属性
				 */
				ajaxGet("/xingshi_xianghun/selectByXingshiId", {
					xingshiId: xingshiId
				}, function (resp) {
					let data = resp.data;

					if (data) {
						$("#property_xingshi_xianghun").html("&emsp;" + data.effect).show();
					}
				}, error);
			}
		}, error);

		if (rowData.taozhuangId > 1 || rowData.waiguanId > 1) {
			$("#property_blue").show();

			if (rowData.taozhuangId > 1) {
				ajaxGet("/chongwu_taozhuang_category/selectById", {
					id: rowData.taozhuangId
				}, function (resp) {
					let data = resp.data;

					$("#property_blue").append("<div>&emsp;套装&ensp;" + data.name + "</div>");
				}, error);
			}
			if (rowData.waiguanId > 1) {
				ajaxGet("/chongwu_waiguan_category/selectById", {
					id: rowData.waiguanId
				}, function (resp) {
					let data = resp.data;

					$("#property_blue").append("<div>&emsp;外观&ensp;" + data.name + "</div>");
				}, error);
			}
		}

		$("#equipment_forger").html(rowData.forger);

		$("#equipment_detail").dialog("open");
	}
}

function deleteHandler() {
	let rowData = $("#equipment_list").datagrid("getSelected");
	
	if (rowData) {
		$.messager.confirm("提示", "是否确认删除？", function(bool) {
			if (bool) {
				ajaxPost("/chongwu_equipment/deleteById", {
					id: rowData.id
				}, function(resp) {
					showMsg(resp.message);

					$("#equipment_list").datagrid("reload");
				}, error);
			}
		});
	} else {
		alertMsg("请选择要删除的记录！");
	}
}

function computeHandler() {
	let rowData = $("#equipment_list").datagrid("getSelected");

	if (rowData) {
		ajaxPost("/chongwu_equipment/compute", {
			equipmentId: rowData.id
		}, function(resp) {
			showMsg(resp.message);

			$("#equipment_list").datagrid("reload");
		}, error);
	} else {
		unselected();
	}
}

$(document).ready(function() {

	$("#categoryId").combobox({
		url: "/chongwu_equipment_category/selectAll",
		valueField: "id",
		textField: "name",
		width: 150,
		required: true,
		panelHeight: "auto",
		formatter: function(row) {
			return "<img width='20' src='" + row.image + "' />&nbsp;" + row.name;
		}
	});

	$("#score").numberspinner({
		min: 0,
		value: 0,
		width: 150,
		required: false
	});

	$("#taozhuangId").combobox({
		url: "/chongwu_taozhuang_category/selectAll",
		valueField: "id",
		textField: "name",
		width: 150,
		required: true,
		panelHeight: "auto",
		onSelect: function(record) {
			if(record) {
				$("#waiguanId").combobox("reload", {
					id: record.waiguanId
				});
			}
		}
	});

	$("#waiguanId").combobox({
		url: "/chongwu_waiguan_category/selectList",
		valueField: "id",
		textField: "name",
		width: 150,
		required: true,
		panelHeight: "auto"
	});

	fetchRoleId(150);

	$("#forger").textbox({
		width: 150,
        required: true
    });
	
	$("#equipment_dialog").dialog({
		title: "宠物装备",
		width: 500,
		height: 300,
		buttons: [{
			iconCls: "icon-save",
			text: "保存",
			handler: function() {
				let selector = "#equipment_form";

				checkForm(selector, function () {
					let data = $(selector).serialize();

					ajaxPost(requestUrl, data, function(resp) {
						showMsg(resp.message);

						$(selector).form("clear");
						$("#equipment_dialog").dialog("close");
						$("#equipment_list").datagrid("reload");
						$("#equipment_datalist").datalist("reload");
					}, error);
				});
			}
		}, {
			iconCls: "icon-cancel",
			text: "取消",
			handler: function() {
				$("#equipment_form").form("clear");
				$("#equipment_dialog").dialog("close");
			}
		}]
	});

	/******************************************************************************************************/

	/**
	 * 宠物装备列表
	 */
	$("#equipment_datalist").datalist({
		url: "/chongwu_equipment/selectAll",
		width: 222,
		height: 308,
		idField: "id",
		valueField: "id",
		textField: "categoryId",
		textFormatter: function(value, rowData, rowIndex) {
			ajaxGet("/chongwu_equipment_category/selectById", {
				id: rowData.categoryId
			}, function(resp) {
				let data = resp.data;

				$("#equip_" + rowData.id).prop({
					"src": data.image,
					"title": data.name
				});
			}, error);

			ajaxGet("/chongwu_taozhuang_category/selectById", {
				id: rowData.taozhuangId
			}, function(resp) {
				let data = resp.data;

				$("#taozhuang_" + rowData.id).html(data.name);
			}, error);

			return "<table>" +
				"<tr>" +
				"<td rowspan='2'><img height='50' id='equip_" +  rowData.id + "' /></td>" +
				"<td>打造：<span>" + rowData.forger + "</span></td>" +
				"</tr>" +
				"<tr>" +
				"<td>套装：<span class='blue' id='taozhuang_" + rowData.id + "'></span></td>" +
				"</tr>" +
				"</table>";
		},
		onSelect: function(rowIndex, rowData) {
			if(rowData) {
				$("#property_list").datagrid("reload", {
					equipmentId: rowData.id
				});
			}
		}
	});

	/**
	 * 宠物装备属性列表
	 */
	$("#property_list").datagrid({
		url: "/chongwu_equipment_attribute/selectByEquipmentId",
		method: "get",
		title: "宠物装备属性列表",
		width: 456,
		height: 276,
		onAfterEdit: function (rowIndex, rowData, changes) { // 结束行内编辑事件
			data = {
				id: rowData.id,
				type: rowData.type,
				equipmentId: rowData.equipmentId,
				propertyId: changes.propertyId ? changes.propertyId : rowData.propertyId,
				propertyValue: changes.propertyValue ? changes.propertyValue : rowData.propertyValue
			};
		},
		toolbar: [{
			iconCls: "icon-add",
			text: "添加",
			handler: function() {
				let rowData = $("#equipment_datalist").datalist("getSelected");

				if(rowData) {
					requestUrl = "/chongwu_equipment_attribute/insert";

					$("#property_list").datagrid("appendRow",{
						equipmentId: rowData.id,
						propertyId: null,
						propertyValue: 1,
						type: null
					});

					let total = $("#property_list").datagrid("getRows").length;

					editingId = total - 1;

					$("#property_list").datagrid("beginEdit", editingId);
				} else {
					unselected("请选择一件器灵~");
				}
			}
		}, "-", {
			iconCls: "icon-edit",
			text: "修改",
			handler: function() {
				let datagrid = $("#property_list");

				if (editingId != null) {
					datagrid.datagrid("selectRow", editingId);
				} else {
					let row = datagrid.datagrid("getSelected");

					if (row) {
						// 获取行索引，这个索引从0开始
						let rowIndex = datagrid.datagrid("getRowIndex", row);

						editingId = rowIndex;
						requestUrl = "/chongwu_equipment_attribute/updateById";

						datagrid.datagrid("beginEdit", rowIndex);

						let $editor = datagrid.datagrid("getEditor", {
							index: rowIndex,
							field: "propertyId"
						});

						let rowData = $("#equipment_list").datagrid("getSelected");

						$($editor.target).combobox("reload", {
							equipmentId: rowData.categoryId
						});
					} else {
						alertMsg("请选择要修改的记录！", "warning");
					}
				}
			}
		}, "-", {
			iconCls: "icon-save",
			text: "保存",
			handler: function() {
				if (editingId != null) {
					// 只有结束编辑才能获取到最新的值
					$("#property_list").datagrid("endEdit", editingId);

					ajaxPost(requestUrl, data, function(resp) {
						editingId = null;

						showMsg(resp.message);

						$("#property_list").datagrid("reload");
					}, error);
				}
			}
		}, "-", {
			iconCls: "icon-cancel",
			text: "取消",
			handler: function() {
				if (editingId != null) {
					$("#property_list").datagrid("cancelEdit", editingId);

					editingId = null;
				}
			}
		}, "-", {
			iconCls: "icon-delete",
			text: "删除",
			handler: function() {
				let rowData = $("#property_list").datagrid("getSelected");

				if(rowData) {
					$.messager.confirm("提示", "是否确认删除？", function(bool) {
						if (bool) {
							ajaxPost("/chongwu_equipment_attribute/deleteById", {
								id: rowData.id
							}, function(resp) {
								showMsg(resp.message);

								$("#property_list").datagrid("reload");
							}, error);
						}
					});
				} else {
					unselected();
				}
			}
		}],
		columns: [[
			{field: "id", hidden: true},
			{field: "equipmentId", hidden: true},
			{field: "propertyId", title: "属性", align: "center", width: 150
				, editor: {
					type: "combobox",
					options: {
						url: "/chongwu_equipment_view_attribute/selectByEquipmentId",
						valueField: "id",
						textField: "name",
						panelHeight: "auto",
						onSelect: function (record) {
							let $editor = $("#property_list").datagrid("getEditor", {
								index: editingId,
								field: "type"
							});

							$($editor.target).combobox("setValue", record.type);
						}
					}
				}
				, formatter: function(value, rowData, rowIndex) {
					if (value) {
						ajaxGet("/property/selectById", {
							id: value
						}, function (resp) {
							let data = resp.data;

							$("#propperty_" + rowIndex).html(data.name);
						}, error);

						return "<span class='blue' id='propperty_" + rowIndex + "'></span>";
					}
				}
			},
			{field: "propertyValue", title: "属性值", align: "center", width: 150
				, editor: {
					type: "numberspinner",
					options: {
						min: 1
					}
				}
			},
			{field: "type", title: "属性类型", align: "center", width: 150
				, editor: {
					type: "combobox",
					options: {
						data: getJsonData(typeArray)
					}
				}
				, formatter: function(value) {
					return "<span>" + typeArray[value] + "</span>";
				}
			}
		]]
	});

	// 宠物装备属性对话框
	$("#property_dialog").dialog({
		title: " "
	});

	/******************************************************************************************************/

	$("#equipment_detail > .splitter").textbox({
		width: 220
	});

	/**
	 * 宠物装备详情对话框
	 */
	$("#equipment_detail").dialog({
		title: " ",
		width: 240
	});

	/******************************************************************************************************/

	/**
	 * 表格体的高度
	 * @type {number}
	 */
	let heigt_body = heigt_tr_with_role_details * 10;
	/**
	 * 表格高度
	 * @type {number}
	 */
	let height_table = heigt_tool + heigt_header + heigt_filter + heigt_body + heigt_footer + heigt_scoll_bar + 2;

	let datagrid = $("#equipment_list").datagrid({
		url: "/chongwu_equipment/selectByPage",
		height: height_table,
		rownumbers: true,
		fitColumns: true,
		pagination: true,
		remoteFilter: true,
		clientPaging: false,
		onHeaderContextMenu: function(e) {
			e.preventDefault();

			if (!columnMenu){
				createColumnMenu("#equipment_list");
			}
			columnMenu.menu("show", {
				left: e.pageX,
				top: e.pageY
			});
		},
		onLoadSuccess: function () {
			let selector = "#equipment_list";
			let fields = getFields(selector);

			if (fields.length > 0) {
				let datagrid = $(selector);

				for (let i = 0; i < fields.length; i++) {
					let field = fields[i];

					// 隐藏未选中的字段
					if (!field.selected) {
						datagrid.datagrid("hideColumn", field.name);
					}
				}

				datagrid.datagrid("fitColumns");
			}
		},
		toolbar: [{
			iconCls: "icon-add",
			text: "添加",
			handler: function() {
				addHandler();
			}
		}, "-", {
			iconCls: "icon-edit",
			text: "修改",
			handler: function() {
				editHandler();
			}
		}, "-", {
			iconCls: "icon-shield",
			text: "属性",
			handler: function() {
				attributeHandler();
			}
		}, "-", {
			iconCls: "icon-delete",
			text: "删除",
			handler: function() {
				deleteHandler();
			}
		}, "-", {
			iconCls: "icon-ok",
			text: "计算评分",
			handler: function() {
				computeHandler();
			}
		}, "-", {
			iconCls: "icon-search",
			text: "预览装备",
			handler: function() {
				viewHandler();
			}
		}],
		columns: [[
			{field: "id", title: "编号", align: "center", hidden: true},
			{field: "categoryId", title: "装备类型", align: "center", width: 100
				, formatter: function(value, rowData, rowIndex) {
					ajaxGet("/chongwu_equipment_category/selectById", {
						id: value
					}, function(resp) {
						let data = resp.data;

						$("#equipment_" + rowIndex).attr("src", data.image).tooltip({
					        position: "right",
					        content: "<span class='white'>" + data.name + "：" + data.note + "</span>",
					        onShow: function() {
					    		$(this).tooltip("tip").css({
					    			backgroundColor: "#666",
					    			borderColor: "#666"
					    		});
					        }
					    });
					}, error);
					
					return "<img height='" + size + "' id='equipment_" + rowIndex + "' />";
				}
			},
			{field: "score", title: "评分", align: "center", width: 100},
			{field: "forger", title: "打造者", align: "center", width: 100},
			{field: "taozhuangId", title: "套装", align: "center", width: 100
				, formatter: function(value, rowData, rowIndex) {
					ajaxGet("/chongwu_taozhuang_category/selectById", {
						id: value
					}, function(resp) {
						let data = resp.data;

						$("#taozhuang_" + rowIndex).html(data.name);
					}, error);

					return "<div class='blue' id='taozhuang_" + rowIndex + "'></div>";
				}
			},
			{field: "waiguanId", title: "外观", align: "center", width: 100
				, formatter: function(value, rowData, rowIndex) {
					ajaxGet("/chongwu_waiguan_category/selectById", {
						id: value
					}, function(resp) {
						let data = resp.data;

						$("#waiguan_" + rowIndex).html(data.name).tooltip({
							position: "left",
							content: "<span class='white'>" + data.name + "：" + data.note + "</span>",
							onShow: function() {
								$(this).tooltip("tip").css({
									backgroundColor: "#666",
									borderColor: "#666"
								});
							}
						});
					}, error);

					return "<div class='blue' id='waiguan_" + rowIndex + "'></div>";
				}
			},
			{field: "chongwuId", title: "宠物", align: "center", width: 100
				, formatter: function(value, rowData, rowIndex) {
					if (value) {
						ajaxGet("/chongwu/selectById", {
							id: value
						}, function (resp) {
							let data = resp.data;

							$("#chongwu_" + rowIndex).attr("title", data.name);

							ajaxGet("/chongwu_category/selectById", {
								id: data.categoryId
							}, function (resp) {
								let data = resp.data;

								$("#chongwu_" + rowIndex).attr("src", data.image);
							}, error);
						}, error);

						return "<img height='" + size + "' id='chongwu_" + rowIndex + "' />";
					} else {
						return "<span>/</span>"
					}
				}
			},
			roleDetailsColumn
		]]
	});

	datagrid.datagrid("enableFilter", [{
		field: "forger",
		type: "textbox",
		operator: ["equal", "contains"]
	}, {
		field: "roleId",
		type: "combobox",
		options: {
			url: "/role_account/selectAll",
			valueField: "id",
			textField: "name",
			panelHeight: "auto",
			formatter: function(row) {
				ajaxGet("/role_category/selectById", {
					id: row.categoryId
				}, function(resp) {
					let data = resp.data;

					$("#modeling_" + row.id).attr("src", data.image);
				}, error);

				return "<img width='18' id='modeling_" + row.id + "' />&nbsp;" + row.name;
			}
		},
		operator: ["equal", "notequal"]
	}, {
		field: "score",
		type: "numberspinner",
		operator: ["equal", "less", "lessorequal", "greater", "greaterorequal"],
		options: {
			min: 1
		}
	}, {
		field: "waiguanId",
		type: "combobox",
		options: {
			url: "/chongwu_waiguan_category/selectAll",
			valueField: "id",
			textField: "name",
			panelHeight: "auto"
		},
		operator: ["equal", "notequal"]
	}, {
		field: "chongwuId",
		type: "combogrid",
		options: {
			url: "/chongwu/selectAll",
			method: "get",
			idField: "id",
			textField: "name",
			panelWidth: 440,
			panelHeight: "auto",
			columns: [[
				{field: "name", title: "宠物名字", align: "center", width: 100},
				{field: "categoryId", title: "宠物类型", align: "center", width: 80,
					formatter: function(value, rowData, rowIndex) {
						ajaxGet("/chongwu_category/selectById", {
							id: value
						}, function(resp) {
							let data = resp.data;

							$("#_chongwu_" + rowIndex).attr({
								"src": data.image,
								"title": data.name
							});
						});

						return "<img height='32' id='_chongwu_" + rowIndex + "' />";
					}
				},
				{field: "grade", title: "等级", align: "center", width: 80,
					formatter: function(value) {
						return "<span>" + value + "级</span>";
					}
				},
				{field: "score", title: "评分", align: "center", width: 80},
				{field: "lifespan", title: "寿命", align: "center", width: 80,
					formatter: function(value) {
						if(value === 0) {
							return "<div>永生</div>";
						} else {
							return "<div>" + value + "</div>";
						}
					}
				}
			]]
		},
		operator: ["equal", "notequal"]
	}, {
		field: "categoryId",
		type: "combobox",
		options: {
			url: "/chongwu_equipment_category/selectAll",
			valueField: "id",
			textField: "name",
			panelHeight: "auto",
			formatter: function(row) {
				return "<img width='20' src='" + row.image + "' />&nbsp;" + row.name;
			}
		},
		operator: ["equal", "notequal"]
	}, {
		field: "taozhuangId",
		type: "combobox",
		options: {
			url: "/chongwu_taozhuang_category/selectAll",
			valueField: "id",
			textField: "name",
			panelHeight: "auto",
		},
		operator: ["equal", "notequal"]
	}]);

});